package com.hobbit.net
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.utils.Dictionary;
	import flash.utils.Timer;

	public class HttpService
	{
		private var _callBackFunDic:Dictionary;
		/**
		 * 纪录响应时间
		 */
		private var _timeOutDic:Dictionary;

		public function get dataRecieved():Function
		{
			return _dataRecieved;
		}

		public function set dataRecieved(value:Function):void
		{
			_dataRecieved = value;
		}

		private var _dataRecieved:Function;
		
		private var _timer:Timer;
		private var _timeOut:int = 30;
		private var numLoads:int = 0;
		
		public function HttpService()
		{
			_callBackFunDic = new Dictionary();
			_timeOutDic = new Dictionary();
			_timer = new Timer(1000);
			_timer.addEventListener(TimerEvent.TIMER, onTimer);
		}
		
		protected function onTimer(event:TimerEvent):void
		{
			for (var key:* in _timeOutDic)
			{
				_timeOutDic[key] += 1;
				if (_timeOutDic[key] > 30)
				{
					delete _callBackFunDic[key];
					removeTimeOut(key);
				}
			}
			if (numLoads <= 0)
				_timer.stop();
		}
		
		public function send(controllerName:String, actionName:String, url:String, data:*, method:String="post", callBack:Function=null, dataFormat:String="binary"):void
		{
			var urlReq:URLRequest = new URLRequest(url);
			urlReq.method = method;
			var urlVariables:URLVariables = new URLVariables();
			urlVariables.c = controllerName;
			urlVariables.a = actionName;
			if (data)
			{
				for (var key:String in data)
				{
					urlVariables[key] = data[key];
				}
			}
			urlReq.data = urlVariables;
			var urlLoader:URLLoader = new URLLoader();
			urlLoader.dataFormat = dataFormat;
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			if (callBack != null)
			{
				_callBackFunDic[urlLoader] = callBack;
				urlLoader.addEventListener(Event.COMPLETE, onComplete);
			}
			urlLoader.load(urlReq);
			_timeOutDic[urlLoader] = 0;
			numLoads++;
			if (!_timer.running) _timer.start();
		}
		
		/**
		 * 移除timeout记录
		 * @param urlLoader
		 * 
		 */
		private function removeTimeOut(urlLoader:URLLoader):void
		{
			delete _timeOutDic[urlLoader];
			numLoads--;
		}
		
		protected function onComplete(event:Event):void
		{
			var urlLoader:URLLoader = event.currentTarget as URLLoader;
			urlLoader.removeEventListener(Event.COMPLETE,onComplete);
			
			var fun:Function = _callBackFunDic[urlLoader];
			_dataRecieved(fun, urlLoader.data);
			delete _callBackFunDic[urlLoader];
			removeTimeOut(urlLoader);
		}
		
		protected function onIOError(event:IOErrorEvent):void
		{
			
		}
	}
}